import {
    StyleSheet,
    Text,
    View,
    Pressable,
    Image,
    TextInput,
    Dimensions,
    ScrollView,
    TouchableOpacity,
    Button,
    VirtualizedList
} from 'react-native'
import React, { useEffect, useRef, useState } from 'react'
import { useRouter, Link, useFocusEffect } from 'expo-router';
import AsyncStorage from '@react-native-async-storage/async-storage'
import Animated, { useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated';
import 'react-native-gesture-handler';
import axios from 'axios';

const { height } = Dimensions.get('window');

// 人均消费数组
const rjxf = [
    {
        id: 1,
        title: "10元以下"
    },
    {
        id: 2,
        title: "10-30元"
    },
    {
        id: 3,
        title: "30元以上"
    }
]
// 商品配送数组
const spps = [
    {
        id: 1,
        title: "顺丰快递"
    },
    {
        id: 2,
        title: "圆通快递"
    },
    {
        id: 3,
        title: "申通快递"
    }
]

export default function Catelist() {

    const router = useRouter();

    const [searchid, setsearchid] = useState('')
    const [sortflag, setsortflag] = useState("综合")
    const [sxprice, setsxprice] = useState('')
    const [sxps, setsxps] = useState('')
    const [searchlist, setsearchlist] = useState([])
    const [sortlist, setsortlist] = useState([])
    const [priceflag, setpriceflag] = useState(true)


    useEffect(() => {
        loadid();
    }, []);

    useEffect(() => {
        if (searchid) {
            search();
        }
    }, [searchid]);

    const loadid = async () => {
        try {
            const id = await AsyncStorage.getItem('itemid');
            if (id) {
                let a = JSON.parse(id)
                setsearchid(a)
            }
        } catch (error) {
            console.error('Error loading history:', error);
        }
    };

    let search = async () => {
        await axios.get('http://192.168.13.227:3000/lzl/getcatelist', {
            params: {
                searchid: searchid
            }
        }).then(res => {
            setsearchlist(res.data);
            setsortlist(res.data)
        })
    }

    const replaceCommasWithPipes = (str: String) => {
        return str.replace(/，/g, ' | ');
    };
    const handleLocalstory = async (item: any) => {
        AsyncStorage.setItem('shopInfo', JSON.stringify(item))
        router.push('/DescPage')
    }

    const zhsort = async () => {
        setsearchlist(sortlist)
    }

    const xlsort = async () => {
        let list = [...sortlist].reverse()

        setsearchlist(list)
    }

    const pricesort = async () => {
        let list = [...sortlist]
        if (priceflag) {
            list.sort((a: any, b: any) => a.price - b.price)
            setsearchlist(list)
            setpriceflag(!priceflag)
        } else {
            list.sort((a: any, b: any) => b.price - a.price)
            setsearchlist(list)
            setpriceflag(!priceflag)
        }
    }

    const drawerHeight = height * 0.4; // 抽屉高度为屏幕高度的60%
    const drawerPosition = useSharedValue(-drawerHeight); // 初始位置在屏幕上方

    const animatedStyle = useAnimatedStyle(() => {
        return {
            transform: [{ translateY: drawerPosition.value }],
        };
    });

    const openDrawer = () => {
        drawerPosition.value = withTiming(0, { duration: 300 }); // 动画打开抽屉
    };

    const closeDrawer = () => {
        drawerPosition.value = withTiming(-drawerHeight, { duration: 300 }); // 动画关闭抽屉
    };


    const sortsx = async () => {
        let list = [...sortlist]

        if (sxps) {
            if (sxprice != "") {
                if (sxprice == "10元以下") {
                    let newlist = list.filter((item: any) => {
                        return item.price <= 10 && item.courier == sxps
                    })
                    closeDrawer()
                    setsearchlist(newlist)

                } else if (sxprice == "10-30元") {
                    let newlist = list.filter((item: any) => {
                        return item.price > 10 && item.price <= 30 && item.courier == sxps
                    })
                    closeDrawer()
                    setsearchlist(newlist)
                } else {
                    let newlist = list.filter((item: any) => {
                        return item.price > 30 && item.courier == sxps
                    })
                    closeDrawer()
                    setsearchlist(newlist)
                }
            } else {
                let newlist = list.filter((item: any) => {
                    return item.courier == sxps
                })
                closeDrawer()
                setsearchlist(newlist)
            }
        } else if (sxprice) {
            if (sxprice == "10元以下") {
                let newlist = list.filter((item: any) => {
                    return item.price <= 10
                })
                closeDrawer()
                setsearchlist(newlist)
            } else if (sxprice == "10-30元") {
                let newlist = list.filter((item: any) => {
                    return item.price > 10 && item.price <= 30
                })
                closeDrawer()
                setsearchlist(newlist)
            } else {
                let newlist = list.filter((item: any) => {
                    return item.price > 30
                })
                closeDrawer()
                setsearchlist(newlist)
            }
        } else {
            setsearchlist(sortlist)
            closeDrawer()
        }

    }


    const renderItem = ({ item }: any) => (
        <Pressable style={styles.shopcar} onPress={() => handleLocalstory(item)}>
            <Image
                style={styles.shopimg}
                source={{ uri: item.img[0] }}
            />
            <View style={{ padding: 10 }}>
                <Text>{item.name}</Text>
                <Text style={{ fontSize: 12, marginTop: 5, color: "#aeaeae" }}>{replaceCommasWithPipes(item.description)}</Text>
                <Text style={{ fontSize: 18, marginTop: 5, color: 'red' }}>
                    <Text style={{ fontSize: 12 }}>￥</Text>
                    {item.price}
                </Text>
            </View>
        </Pressable>
    );

    return (
        <ScrollView style={[{ backgroundColor: "#f2f6fd" }]}>

            <View style={styles.Input}>
                <Pressable onPress={() => router.push('/home')}>
                    <Image source={require("@/assets/img/左箭头.png")} />
                </Pressable>
                <TextInput
                    style={styles.search}
                    placeholder='精选天然水果'
                    onFocus={() => (
                        router.push('/HomeModel/Search')
                    )}
                />
                <View style={{ backgroundColor: "#99cc33", borderRadius: 100 }}>
                    <Text
                        style={{ paddingHorizontal: 10, paddingVertical: 5, color: "#99cc33" }}

                    >搜索</Text>
                </View>
            </View>

            <View style={{
                flexDirection: "row", justifyContent: "space-evenly",
                paddingTop: 10, backgroundColor: "#ffffff", paddingBottom: 10,
            }}>
                <Text
                    onPress={() => (setsortflag("综合"), zhsort())}
                    style={sortflag == "综合" ?
                        {
                            color: "#99cc33",
                            borderBottomColor: "#99cc33",
                            borderBottomWidth: 3,
                        }
                        :
                        {}
                    }>
                    综合
                </Text>
                <Text
                    onPress={() => (setsortflag("销量"), xlsort())}
                    style={sortflag == "销量" ?
                        {
                            color: "#99cc33",
                            borderBottomColor: "#99cc33",
                            borderBottomWidth: 3,
                        }
                        :
                        {}
                    }>
                    销量
                </Text>
                <Text
                    onPress={() => (setsortflag("价格"), pricesort())}
                    style={sortflag == "价格" ?
                        {
                            color: "#99cc33",
                            borderBottomColor: "#99cc33",
                            borderBottomWidth: 3,
                        }
                        :
                        {}
                    }>
                    价格
                </Text>
                <Text
                    onPress={() => (setsortflag("筛选"), openDrawer())}
                    style={sortflag == "筛选" ?
                        {
                            color: "#99cc33",
                            borderBottomColor: "#99cc33",
                            borderBottomWidth: 3,
                        }
                        :
                        {}
                    }>
                    筛选
                </Text>
            </View>

            {/* 抽屉 */}
            <Animated.View style={[styles.drawer, animatedStyle]}>
                <TouchableOpacity onPress={closeDrawer} style={styles.closeButton}>
                    <Text style={styles.closeButtonText}>关闭</Text>
                </TouchableOpacity>
                <View style={{ width: "80%", marginLeft: "10%", marginTop: 10 }}>
                    <Text
                        style={{
                            borderLeftWidth: 3,
                            borderColor: "#99cc33",
                            paddingHorizontal: 5
                        }}>
                        人均消费
                    </Text>
                    <View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 10 }}>
                        {
                            rjxf.map((item: any) => (
                                <Text key={item.id}
                                    onPress={() => (
                                        setsxprice(item.title)
                                    )}
                                    style={sxprice === item.title ?
                                        {
                                            backgroundColor: "#99cc33",
                                            color: "#ffffff",
                                            paddingHorizontal: 14,
                                            paddingVertical: 5,
                                            borderRadius: 2,
                                        }
                                        :
                                        {
                                            backgroundColor: "#e4e4e4",
                                            paddingHorizontal: 14,
                                            paddingVertical: 5,
                                            borderRadius: 2,
                                        }}
                                >{item.title}</Text>
                            ))
                        }
                    </View>
                </View>
                <View style={{ width: "80%", marginLeft: "10%", marginTop: 10 }}>
                    <Text
                        style={{
                            borderLeftWidth: 3,
                            borderColor: "#99cc33",
                            paddingHorizontal: 5
                        }}>
                        商品配送
                    </Text>
                    <View style={{ flexDirection: "row", justifyContent: "space-between", marginTop: 10 }}>
                        {
                            spps.map((item: any) => (
                                <Text key={item.id}
                                    onPress={() => (
                                        setsxps(item.title)
                                    )}
                                    style={sxps === item.title ?
                                        {
                                            backgroundColor: "#99cc33",
                                            color: "#ffffff",
                                            paddingHorizontal: 14,
                                            paddingVertical: 5,
                                            borderRadius: 2,
                                        }
                                        :
                                        {
                                            backgroundColor: "#e4e4e4",
                                            paddingHorizontal: 14,
                                            paddingVertical: 5,
                                            borderRadius: 2,
                                        }}
                                >{item.title}</Text>
                            ))
                        }
                    </View>
                </View>
                <View style={{ flexDirection: 'row', position: "absolute", bottom: 0, width: "100%", }}>
                    <View style={[{ backgroundColor: "#ffffff", width: "50%", borderBottomLeftRadius: 10 }]}>
                        {/* 清空 */}
                        <Text
                            onPress={() => { setsxprice(''), setsxps('') }}
                            style={{
                                color: "#000", marginLeft: "auto",
                                marginRight: "auto", paddingVertical: 10
                            }}>清空</Text>
                    </View>
                    <View style={[{ backgroundColor: "#99cc33", width: "50%", borderBottomRightRadius: 10 }]}>
                        {/* 确定 */}
                        <Text
                            onPress={() => { sortsx() }}
                            style={{
                                color: "#fff", marginLeft: "auto",
                                marginRight: "auto", paddingVertical: 10
                            }}>确定</Text>
                    </View>
                </View>
            </Animated.View >

            {
                searchlist.length > 0 ?
                    <View style={[styles.Itemflex]}>

                        {/* <VirtualizedList
                        contentContainerStyle={[styles.virtualizedList]}
                        data={searchlist}
                        initialNumToRender={10}
                        renderItem={renderItem}
                        keyExtractor={(item: any) => item._id}
                        getItemCount={() => searchlist.length}
                        getItem={(data, index) => data[index]}
                    /> */}
                        {
                            searchlist.map((item: any) => (
                                <Pressable style={styles.shopcar} onPress={() => handleLocalstory(item)}>
                                    <Image
                                        style={styles.shopimg}
                                        source={{ uri: item.img[0] }}
                                    />
                                    <View style={{ padding: 10 }}>
                                        <Text>{item.name}</Text>
                                        <Text style={{ fontSize: 12, marginTop: 5, color: "#aeaeae" }}>{replaceCommasWithPipes(item.description)}</Text>
                                        <Text style={{ fontSize: 18, marginTop: 5, color: 'red' }}>
                                            <Text style={{ fontSize: 12 }}>￥</Text>
                                            {item.price}
                                        </Text>
                                    </View>
                                </Pressable>
                            ))
                        }
                    </View>

                    :
                    <View style={styles.Itemflex}>
                        <Text style={{ textAlign: "center", marginTop: 20, color: "#b8b8b8" }} >~什么都没有了哦~</Text>
                    </View>
            }
        </ScrollView >
    )
}

const styles = StyleSheet.create({
    Input: {
        height: 60,
        backgroundColor: "#99cc33",
        position: "relative",
        display: "flex",
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-evenly",
        // alignItems:"flex-start",
    },
    search: {
        width: Dimensions.get('window').width - Dimensions.get('window').width / 2.5,
        borderWidth: 0,
        paddingHorizontal: 15,
        paddingVertical: 5,
        borderRadius: 50,
        backgroundColor: '#fff',
    },
    Itemflex: {
        // display: 'flex',
        flexWrap: 'wrap',
        width: 310,
        // height: 1000,
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginLeft: 'auto',
        marginRight: 'auto',
        zIndex: 1
    },
    shopcar: {
        width: 150,
        marginTop: 10,
        backgroundColor: '#fff',
        borderRadius: 10,
    },
    shopimg: {
        width: 150,
        height: 100,
        borderTopLeftRadius: 10,
        borderTopRightRadius: 10
    },
    drawer: {
        ...StyleSheet.absoluteFillObject,
        top: 0,
        left: 0,
        right: 0,
        height: 256,
        backgroundColor: 'white',
        borderBottomLeftRadius: 20,
        borderBottomRightRadius: 20,
        shadowColor: '#000',
        shadowOffset: { width: 0, height: -2 },
        shadowOpacity: 0.5,
        shadowRadius: 5,
        elevation: 10,
        zIndex: 1001,
    },
    closeButton: {
        alignSelf: 'flex-end',
        padding: 10,
    },
    closeButtonText: {
        color: '#007BFF',
        fontSize: 16,
    },
    drawerContent: {
        padding: 20,
        marginTop: 20,
    },
    virtualizedList: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        justifyContent: "space-around",
        backgroundColor: '#f0f0f0', // 背景颜色
    },
})